package com.zcsy.manage.web.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.ManageConstants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.commons.util.PoiUtils;
import com.zcsy.manage.model.base.CellBuilding;
import com.zcsy.manage.model.base.CellHouse;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.CellRegion;
import com.zcsy.manage.model.base.CellUnit;
import com.zcsy.manage.model.base.OwnerHouse;
import com.zcsy.manage.model.mall.OwnerAddress;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.weixin.StringUtil;
import com.zcsy.manage.service.base.ICellBuildingService;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.ICellRegionService;
import com.zcsy.manage.service.base.ICellUnitService;
import com.zcsy.manage.service.base.IOwnerHouseService;
import com.zcsy.manage.service.mall.IOwnerAddressService;
import com.zcsy.manage.service.property.ICarBillService;
import com.zcsy.manage.service.property.IFeeBillService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.service.system.IUserService;
import com.zcsy.manage.web.common.LogUtils;
import com.zcsy.manage.web.tools.JExcelReport;

/**
 * @Title: CellHouseController.java @Package： com.zcsy.manage.web.base
 * @Description: 小区房屋信息controller层
 *
 * @author caiyinli 13277030520@163.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年4月6日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */

@Controller
@RequestMapping(value = "/cellHouse")
public class CellHouseController {

    @Autowired
    private ICellHouseService cellHouseService;

    @Autowired
    private IDictService dictService;

    @Autowired
    private ICellRegionService cellRegionService;

    @Autowired
    private ICellBuildingService cellBuildingService;

    @Autowired
    private ICellInfoService cellInfoService;

    @Autowired
    private ICellUnitService cellUnitService;

    @Autowired
    private IOwnerAddressService ownerAddressService;

    @Autowired
    private IOwnerHouseService ownerHouseService;
    
    @Autowired
    private IFeeBillService feeBillService;
    
    @Autowired
    private ICarBillService carBillService;
    
    @Autowired
    private IUserService userService;

    /** 新申请 */
    private static final int STATE_NEW = 1;
    /** 审核通过 */
    private static final int STATE_SUCCESS = 2;
    /** 审核未通过 */
    private static final int STAET_NOTAPPROVE = 4;

    /**
     * @Description 房屋信息关键字检索<br>
     * 
     * @param model
     * @param pNo
     *            当前页码
     * @param name
     *            房屋名称
     * @param houseType
     *            房屋类型
     * @param houseState
     *            房屋状态
     * @param req
     *            用户请求
     * @return 返回房屋信息学列表页面
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月7日
     * @see
     */
    @RequestMapping(value = "cellHouseList", method = RequestMethod.GET)
    public String cellInfoList(Model model, Integer pNo, Integer pSize, String keyword, Integer houseType,
            Integer houseState, String regionId, HttpServletRequest req) {

        if (pNo == null) {
            pNo = Constants.PAGE_NO;
        }

        Integer pageSize;
        if (pSize == null) {
            pageSize = Constants.PAGE_SIZE;
        } else {
            switch (pSize) {
            case 0:
                pageSize = Constants.PAGE_SIZE;
                break;
            case 1:
                pageSize = Constants.PAGE_SIZE_TWENTY;
                break;
            case 2:
                pageSize = Constants.PAGE_SIZE_FIFTY;
                break;
            default:
                pageSize = Constants.PAGE_SIZE;
                break;
            }
        }

        if (houseType == null) {
            houseType = ManageConstants.HOUSE_TYPE;
        }

        if (houseState == null) {
            houseState = ManageConstants.HOUSE_STATE;
        }

        CellHouse cellHouse = new CellHouse();

        if (StringUtils.isNotEmpty(keyword)) {
            cellHouse.setKeyword(keyword);
        }

        cellHouse.setHouseType(houseType);
        cellHouse.setHouseState(houseState);

        if (StringUtils.isNotEmpty(regionId)) {
            cellHouse.setRegionId(regionId);

            CellRegion cellRegion = cellRegionService.selectByPrimaryKey(regionId);
            cellHouse.setRegionName(cellRegion.getName());
        }

        // 获取当前小区信息
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        cellHouse.setCellId(cellId);

        CellInfo cellInfo = cellInfoService.selectByPrimaryKey(cellId);
        model.addAttribute("cellInfos", cellInfo);

        cellHouse.setRegionName(cellInfo.getCellName());

        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);

        List<CellHouse> cellHouses = cellHouseService.selectByKeyword(cellHouse);
        PageInfo<CellHouse> info = new PageInfo<CellHouse>(cellHouses);

        model.addAttribute("cellHouse", info);
        model.addAttribute("currentPage", pNo);
        model.addAttribute("pSize", pSize);
        model.addAttribute("keyword", keyword);
        model.addAttribute("houseType", houseType);
        model.addAttribute("houseState", houseState);
        model.addAttribute("regionId", regionId);

        // 从缓存中获取房屋类型
        List<Dict> houseTypes = dictService.getDictFromCache("houseType");
        model.addAttribute("houseTypes", houseTypes);

        // 从缓存中获取房屋状态
        List<Dict> houseStates = dictService.getDictFromCache("houseState");
        model.addAttribute("houseStates", houseStates);

        // 获取当前小区的区域
        List<CellRegion> cellRegions = cellRegionService.getCellRegionByCellId(cellId);
        model.addAttribute("cellRegions", cellRegions);

        List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
        model.addAttribute("pageSizes", pageSizes);

        return "base/cellhouse/cellHouseList";
    }

    /**
     * @Description 编辑或新增房屋信息页面<br>
     * @param model
     * @param id
     *            主键id id为0表示新增 ；id不为0表示编辑
     * @return 编辑或新增房屋信息页面
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月7日
     * @see
     */
    @RequestMapping(value = "editCellHouse", method = RequestMethod.GET)
    public String selectById(Model model, String id, HttpServletRequest req) {
        try {
            if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
                model.addAttribute("type", Constants.SAVE_TYPE);
            } else {
                CellHouse cellHouse = cellHouseService.selectByPrimaryKey(id);
                if (cellHouse != null) {
                    model.addAttribute("type", Constants.EDIT_TYPE);
                    model.addAttribute("cellHouse", cellHouse);
                }
            }

            User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            String cellid = user.getCurrentCell().getId();
            List<CellRegion> cellRegions = cellRegionService.getCellRegionByCellId(cellid);
            model.addAttribute("cellRegions", cellRegions);

            // 从缓存不为空则从缓存中获取房屋类型，为空测从数据字典获取
            List<Dict> houseTypes = dictService.getDictFromCache("houseType");
            if (houseTypes != null && houseTypes.size() > 0) {
                model.addAttribute("houseTypes", houseTypes);
            } else {
                List<Dict> dictList = dictService.selectByType("houseType");
                model.addAttribute("houseTypes", dictList);
            }

            // 从缓存中获取房屋状态
            List<Dict> houseStates = dictService.getDictFromCache("houseState");
            model.addAttribute("houseStates", houseStates);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "base/cellhouse/cellHouseEdit";
    }

    /**
     * @Description 保存或更新房屋信息<br>
     * @param name
     *            房屋名称
     * @param houseType
     *            房屋类型
     * @param houseState
     *            房屋状态
     * @param houseId
     *            房屋id
     * @param area
     *            房屋面积
     * @param perPrice
     *            房屋单价
     * @param request
     *            用户请求
     * @param response
     *            相应
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月7日
     * @see
     */
    @RequestMapping(value = "saveOrUpdateCellHouse", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdateCellHouse(String name, String regionId, String buildingId, String unitId,
            Integer houseType, Integer houseState, String houseId, BigDecimal area, BigDecimal perPrice,
            /* Integer sort, */String ownerName1, String ownerPhone1, String ownerName2, String ownerPhone2,
            HttpServletRequest request, HttpServletResponse response) {
        RequestJson result = new RequestJson();
        User user = (User) request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        try {
            CellHouse record = new CellHouse();
            record.setName(name);
            record.setHouseType(houseType);
            record.setHouseState(houseState);
            record.setArea(area);
            record.setPerPrice(perPrice);
            /* record.setSort(sort); */
            record.setOwnerName1(ownerName1);
            record.setOwnerPhone1(ownerPhone1);
            record.setOwnerName2(ownerName2);
            record.setOwnerPhone2(ownerPhone2);
            record.setUserAccount(user.getLoginname());

            // 检验名称是否存在
            boolean isUpdate = (houseId != null && !"0".equals(houseId));
            if (StringUtil.isEmptyString(unitId)) {
                unitId = cellHouseService.selectByPrimaryKey(houseId).getUnitId();
            }
            boolean nameExists = cellHouseService.isNameExists(isUpdate ? houseId : null, unitId, name);
            if (nameExists) {
                result.setSuccess(false);
                result.setMsg("房屋名称已存在");
            } else {
                if (isUpdate) {
                    record.setId(houseId);
                    record.setUpdateTime(new Date());

                    record.setRegionId(regionId);
                    if (regionId != null) {
                        record.setRegionName(cellRegionService.selectByPrimaryKey(regionId).getName());
                    }
                    record.setBuildingId(buildingId);
                    if (buildingId != null) {
                        record.setBuildingName(cellBuildingService.selectByPrimaryKey(buildingId).getBuildingName());
                    }
                    record.setUnitId(unitId);
                    if (unitId != null) {
                        record.setUnitName(cellUnitService.selectByPrimaryKey(unitId).getName());
                    }
                    cellHouseService.update(record);
                    LogUtils.insertLog("用户修改小区房屋信息", user.getId(), request);

                } else {
                    record.setId(UniqueNumberUtils.get18UniqueNumber());
                    record.setSendTime(new Date());
                    record.setCellId(cellId);

                    if (cellId != null) {
                        record.setCellName(cellInfoService.selectByPrimaryKey(cellId).getCellName());
                    }
                    record.setRegionId(regionId);
                    if (regionId != null) {
                        record.setRegionName(cellRegionService.selectByPrimaryKey(regionId).getName());
                    }
                    record.setBuildingId(buildingId);
                    if (buildingId != null) {
                        record.setBuildingName(cellBuildingService.selectByPrimaryKey(buildingId).getBuildingName());
                    }
                    record.setUnitId(unitId);
                    if (unitId != null) {
                        record.setUnitName(cellUnitService.selectByPrimaryKey(unitId).getName());
                    }
                    cellHouseService.insert(record);
                    LogUtils.insertLog("用户新增小区房屋信息", user.getId(), request);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * @Description 删除房屋信息<br>
     * @param houseIDs 需要删除的主键id组成的字符串
     * @param req 用户请求
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月7日
     * @see
     */
    @RequestMapping(value = "deleteCellHouse", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deletePage(@RequestParam("houseIDs[]") String[] houseIDs, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {
            Integer oHouseCount = ownerHouseService.selectByHouseIds(houseIDs);
            Integer fbillCount = feeBillService.selectByHouseIds(houseIDs);
            Integer cbillCount = carBillService.selectByHouseIds(houseIDs);
            if (oHouseCount > 0 || fbillCount > 0 || cbillCount > 0) {
            	result.setMsg("房屋已被引用，不能删除！");
				result.setSuccess(false);
			} else {
				cellHouseService.deleteByPrimaryKey(houseIDs);
	            result.setSuccess(true);
	            LogUtils.insertLog("用户删除小区房屋信息", user.getId(), req);
			}
            
        } catch (NumberFormatException e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * @Description 通过小区id获取该小区下面的所有区域，做级联时使用<br>
     * @param cellId
     *            小区id
     * @param req
     *            用户请求
     * @return 返回该小区的区域集合
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see
     */
    @RequestMapping(value = "/getCellRegionByCellId", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson getCellRegionByCellId(String cellId, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
            List<CellRegion> cellRegionList = cellRegionService.getCellRegionByCellId(cellId);
            result.setObj(cellRegionList);
        } catch (Exception e) {
            result.setMsg("操作异常");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @Description 通过区域id获取该区域下的所有楼栋，级联时使用<br>
     * @param regionId
     *            区域id
     * @param req
     *            用户请求
     * @return 返回该区域下的所有楼栋集合
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see
     */
    @RequestMapping(value = "/getCellBuildingByRegionId", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson getCellBuildingByRegionId(String regionId, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
            List<CellBuilding> cellBuildingList = cellBuildingService.getCellBuildingByRegionId(regionId);
            result.setObj(cellBuildingList);
        } catch (Exception e) {
            result.setMsg("操作异常");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @Description 通过楼栋id获取所有改楼栋下的单元，级联时使用<br>
     * @param buildingId
     *            楼栋id
     * @param req
     *            用户请求
     * @return 返回该楼栋下的所有单元集合
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see
     */
    @RequestMapping(value = "/getCellUnitByBuildingId", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson getCellUnitByBuildingId(String buildingId, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
            List<CellUnit> cellUnitList = cellUnitService.getCellUnitByBuildingId(buildingId);
            result.setObj(cellUnitList);
        } catch (Exception e) {
            result.setMsg("操作异常");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @Description 房屋管理信息详情
     * @author fangli Fanglwj520@163.com
     * @date 2016年5月17日
     */
    @RequestMapping(value = "/cellHouseDetail", method = RequestMethod.GET)
    public String cellInfoDetail(Model model, String id, HttpServletRequest req) {
        try {
            CellHouse cellHouse = cellHouseService.selectByPrimaryKey(id);
            if (cellHouse != null) {
                model.addAttribute("cellHouse", cellHouse);
            }
        } catch (Exception e) {
        }

        return "base/cellhouse/cellHouseDetail";
    }

    /**
     * @Description 根据排序实现置顶功能，即修改当前排序为最大排序值加1，并且更新修改时间<br>
     * @param id
     *            商品id
     * @param req
     *            用户请求
     * @author caiyinli 13277030520@163.com
     * @date 2016年6月3日
     */
    /*@RequestMapping(value = "updateSort", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson updateSort(String id, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {
            CellHouse cellHouse = cellHouseService.selectByPrimaryKey(id);
            if (cellHouse != null) {
                cellHouse.setUpdateTime(DateUtils.getDate());
                cellHouseDao.updateSort(cellHouse);
            }
            LogUtils.insertLog("用户置顶小区房屋", user.getId(), req);
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setSuccess(false);
        }

        return result;
    }*/

    /**
     * @description 返回房屋申请列表信息
     * @author chenxin
     * @date 2016年8月18日上午11:14:19
     */
    @RequestMapping(value = "cellHouseApplication", method = RequestMethod.GET)
    public String cellHouseApplication(Model model, Integer pNo, Integer pSize, String name, Integer houseType,
            Integer houseState, String regionId, Integer state, HttpServletRequest req) {

        if (pNo == null) {
            pNo = Constants.PAGE_NO;
        }

        Integer pageSize;
        if (pSize == null) {
            pageSize = Constants.PAGE_SIZE;
        } else {
            switch (pSize) {
            case 0:
                pageSize = Constants.PAGE_SIZE;
                break;
            case 1:
                pageSize = Constants.PAGE_SIZE_TWENTY;
                break;
            case 2:
                pageSize = Constants.PAGE_SIZE_FIFTY;
                break;
            default:
                pageSize = Constants.PAGE_SIZE;
                break;
            }
        }

        if (houseType == null) {
            houseType = ManageConstants.HOUSE_TYPE;
        }

        if (houseState == null) {
            houseState = ManageConstants.HOUSE_STATE;
        }

        CellHouse cellHouse = new CellHouse();

        if (StringUtils.isNotEmpty(name)) {
            cellHouse.setName(name);
        }

        cellHouse.setHouseType(houseType);
        cellHouse.setHouseState(houseState);

        if (StringUtils.isNotEmpty(regionId)) {
            cellHouse.setRegionId(regionId);

            CellRegion cellRegion = cellRegionService.selectByPrimaryKey(regionId);
            cellHouse.setRegionName(cellRegion.getName());
        }

        // 获取当前小区信息
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        cellHouse.setCellId(cellId);

        CellInfo cellInfo = cellInfoService.selectByPrimaryKey(cellId);
        model.addAttribute("cellInfos", cellInfo);
        
        if(null == state) {
            state = STATE_NEW;
            cellHouse.setState(STATE_NEW);
        } else {
            cellHouse.setState(state);
        }
        
        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);

        List<CellHouse> cellHouses = cellHouseService.selectByKeyWordCommand(cellHouse);
        PageInfo<CellHouse> info = new PageInfo<CellHouse>(cellHouses);

        model.addAttribute("cellHouse", info);
        model.addAttribute("currentPage", pNo);
        model.addAttribute("pSize", pSize);
        model.addAttribute("name", name);
        model.addAttribute("houseType", houseType);
        model.addAttribute("houseState", houseState);
        model.addAttribute("regionId", regionId);
        model.addAttribute("applyState", state);

        // 从缓存中获取房屋类型
        List<Dict> houseTypes = dictService.getDictFromCache("houseType");
        model.addAttribute("houseTypes", houseTypes);

        // 从缓存中获取房屋状态
        List<Dict> houseStates = dictService.getDictFromCache("houseState");
        model.addAttribute("houseStates", houseStates);

        // 获取当前小区的区域
        List<CellRegion> cellRegions = cellRegionService.getCellRegionByCellId(cellId);
        model.addAttribute("cellRegions", cellRegions);

        List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
        model.addAttribute("pageSizes", pageSizes);
        
        List<Dict> applyingState = dictService.getDictFromCache("approveStateOfOwner");
        model.addAttribute("applyingState", applyingState);
        
        return "base/cellhouse/cellHouseApplication";
    }

    /**
     * @description 房屋审核
     * @param id 房屋id
     * @author chenxin
     * @date 2016年8月18日上午11:12:50
     */
    @RequestMapping(value = "/cellHouseUpdating", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson cellHouseUpdating(Model model, String ownerId, String ownerHouseId, String id, int state, String detailAddress,
            String regionId, String buildingId, String unitId, String recepientName, String recepientPhone,
            HttpServletRequest req) {

        RequestJson result = new RequestJson();

        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        CellInfo cellInfo = user.getCurrentCell();
        String cellId = cellInfo.getId();

        try {
            switch (state) {
            case STATE_SUCCESS:
                state = STATE_SUCCESS;
                break;
            case STAET_NOTAPPROVE:
                state = STAET_NOTAPPROVE;
                break;
            default:
                state = STAET_NOTAPPROVE;
                break;
            }
            // cellHouseService.updateOHouseStateByOwnerIdAndHouseId(cellId, id,
            // state);
            OwnerHouse record = new OwnerHouse();
            record.setId(ownerHouseId);
            record.setCellId(cellId);
            record.setHouseId(id);
            record.setOwnerId(ownerId);
            record.setState(state);
            ownerHouseService.updateOwnerHouse(record);
            LogUtils.insertLog("用户审核小区房屋", user.getId(), req);
            
            User owner = userService.selectByPrimaryKey(ownerId);
            // 房屋申请通过后自动添加到地址表
            OwnerAddress ownerAddress = new OwnerAddress();
            ownerAddress.setId(UniqueNumberUtils.get18UniqueNumber());
            ownerAddress.setOwnerId(ownerId);
            ownerAddress.setProvinceId(cellInfo.getProvinceId().toString());
            ownerAddress.setCityId(cellInfo.getCityId().toString());
            ownerAddress.setAreaId(cellInfo.getAreaId().toString());
            ownerAddress.setCellId(cellInfo.getId());
            ownerAddress.setRegionId(regionId);
            ownerAddress.setBuildingId(buildingId);
            ownerAddress.setUnitId(unitId);
            ownerAddress.setHouseId(id);
            ownerAddress.setDetailAddress(detailAddress);
            ownerAddress.setRecepientName(owner.getUsername());
            ownerAddress.setRecepientPhone(owner.getPhone());
            ownerAddress.setDefaultFlag(Constants.STATE_ENABLED);

            ownerAddressService.insertAddress(ownerAddress);
            LogUtils.insertLog("自动添加一条收货地址", user.getId(), req);
            
            Integer numberOfApplying = cellHouseService.countApply(cellId);
            result.setObj(numberOfApplying);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @Description 导入界面弹框
     * @return 跳转画面
     * @author liuying 1075817474@qq.com
     * @date 2016年8月22日
     * @see
     */
    @RequestMapping(value = "initList", method = RequestMethod.GET)
    public String initList(Model model, HttpServletRequest req) {

        // 获取当前小区信息
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        String url = "";
        try {
            CellInfo cellInfo = cellInfoService.selectByPrimaryKey(cellId);
            model.addAttribute("cellInfo", cellInfo);
            url = "base/cellhouse/initList";
        } catch (Exception e) {
        }

        return url;
    }

    /**
     * @description 导入小区房屋
     * @author chenxin
     * @date 2016年8月26日上午10:36:42
     */
    @RequestMapping("/importCellHouse")
    @ResponseBody
    public RequestJson importCellHouse(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        RequestJson json = new RequestJson();
        // 获取当前小区信息
        User user = (User) request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        // 从缓存中获取房屋类型和房屋状态
        List<Dict> houseTypes = dictService.getDictFromCache("houseType");
        List<Dict> houseStates = dictService.getDictFromCache("houseState");

        List<String> errorMsg = null;

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile imgFile = multipartRequest.getFile("fileIds");

        CommonsMultipartFile cf = (CommonsMultipartFile) imgFile;
        DiskFileItem fi = (DiskFileItem) cf.getFileItem();
        File f = fi.getStoreLocation();

        String fileNames = imgFile.getOriginalFilename();
        long fileSize = imgFile.getSize();
        String extend = fileNames.substring(fileNames.lastIndexOf(".") + 1);

        if (!"xls".equalsIgnoreCase(extend) && !"xlsx".equalsIgnoreCase(extend)) {// 文件格式
            json.setSuccess(false);
            json.setMsg("请选择excel格式文件上传！");
        } else if (fileSize > 1024 * 1024 * 10) {// 文件大小(2Mb)
            json.setSuccess(false);
            json.setMsg("导入文件大小不得大于10Mb！");
        } else {
            InputStream inputStream = null;
            try {
                InputStream is = new FileInputStream(f);
                // 解析xls
                List<List> list = PoiUtils.parseExcelToString(is, 13, 1, 0);
                if (!list.isEmpty()) {
                    // 检查数据格式是否有错
                    errorMsg = cellHouseService.findBug(cellId, list);

                    if (errorMsg == null || errorMsg.size() == 0) {
                        // 校验成功
                        List<CellUnit> cellUnits = cellUnitService.getCellUnitByCellId(cellId);
                        Map<String, CellUnit> map = new HashMap<String, CellUnit>();
                        for (CellUnit item : cellUnits) {
                            String key = new StringBuffer(item.getRegionName()).append(item.getBuildingName())
                                    .append(item.getName()).toString();
                            map.put(key, item);
                        }
                        List<CellHouse> cellHouses = new ArrayList<CellHouse>();
                        CellHouse cellHouse = null;
                        for (List item : list) {
                            String key = new StringBuffer(item.get(0).toString()).append(item.get(1).toString())
                                    .append(item.get(2).toString()).toString();
                            // 插入数据到小区房屋表
                            cellHouse = new CellHouse();

                            cellHouse.setId(UniqueNumberUtils.get18UniqueNumber());
                            cellHouse.setCellId(cellId);
                            cellHouse.setRegionId(map.get(key).getRegionId());
                            cellHouse.setBuildingId(map.get(key).getBuildingId());
                            cellHouse.setUnitId(map.get(key).getId());
                            cellHouse.setCellName(map.get(key).getCellName());
                            cellHouse.setRegionName(item.get(0).toString());
                            cellHouse.setBuildingName(item.get(1).toString());
                            cellHouse.setUnitName(item.get(2).toString());
                            cellHouse.setName(item.get(3).toString());
                            for (Dict houseType : houseTypes) {
                                if (item.get(4).toString().equals(houseType.getLabel())) {
                                    cellHouse.setHouseType(houseType.getValue());
                                    break;
                                }
                            }
                            for (Dict houseState : houseStates) {
                                if (item.get(5).toString().equals(houseState.getLabel())) {
                                    cellHouse.setHouseState(houseState.getValue());
                                    break;
                                }
                            }
                            cellHouse.setArea(new BigDecimal(item.get(6).toString()));
                            cellHouse.setPerPrice(new BigDecimal(item.get(7).toString()));
                            cellHouse.setOwnerName1(item.get(8).toString());
                            cellHouse.setOwnerPhone1(item.get(9).toString());
                            cellHouse.setOwnerName2(item.get(10).toString());
                            cellHouse.setOwnerPhone2(item.get(11).toString());
                            cellHouse.setUserAccount(user.getLoginname());
                            cellHouse.setSendTime(new Date());
                            cellHouse.setSort(Constants.SORT_DEFAULT);
                            cellHouse.setMemo(item.get(12).toString());
                            cellHouses.add(cellHouse);
                        }

                        cellHouseService.insertAll(cellHouses);
                        json.setSuccess(true);
                        json.setMsg("文件导入成功！");
                        LogUtils.insertLog("用户导入小区房屋表格", user.getId(), request);
                    } else {
                        json.setSuccess(false);
                        StringBuffer buffer = new StringBuffer();

                        if (errorMsg != null && errorMsg.size() > 0) {
                            for (int i = 0; i < errorMsg.size(); i++) {
                                buffer.append(errorMsg.get(i) + "</br>");
                            }
                        }
                        json.setObj(errorMsg);
                    }
                } else {
                    json.setSuccess(false);
                    json.setMsg("文件数据错误！");
                }

            } catch (Exception e) {
                json.setSuccess(false);
                json.setMsg("文件格式错误！");
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
        }

        return json;
    }

    /**
     * @Description 导出小区房屋表格
     * @param name
     *            房屋名称
     * @param houseType
     *            房屋类型
     * @param houseState
     *            房屋状态
     * @param regionId
     *            区域id
     * @author liuying 1075817474@qq.com
     * @date 2016年8月24日
     * @see
     */
    @RequestMapping("/exportCellHouseExcel")
    @ResponseBody
    public void exportCellHouseExcel(String name, Integer houseType, Integer houseState, String keyword,
            String regionId, HttpServletRequest request, HttpServletResponse response) {
        List<CellHouse> list;

        if (houseType == null) {
            houseType = ManageConstants.HOUSE_TYPE;
        }

        if (houseState == null) {
            houseState = ManageConstants.HOUSE_STATE;
        }

        CellHouse record = new CellHouse();

        // 标题不为空时，设置标题
        if (StringUtils.isNotEmpty(name)) {
            record.setName(name);
        }
        // 获取当前小区信息
        User user = (User) request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();

        record.setHouseType(houseType);
        record.setHouseState(houseState);
        record.setCellId(cellId);
        record.setKeyword(keyword);

        try {
            // 得到导出的数据列表
            list = cellHouseService.selectByKeyword(record);

            // 将小区房屋对象转化为到处所需要的数据格式
            Integer type, state;
            String tLabel, sLabel;
            if (list.size() > 0) {
                ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();
                int index = 1;
                for (CellHouse cellHouse : list) {
                    ArrayList<String> temp = new ArrayList<String>();
                    // 序号
                    temp.add(String.valueOf(index++));
                    temp.add(cellHouse.getRegionName());
                    temp.add(cellHouse.getBuildingName());
                    temp.add(cellHouse.getUnitName());
                    temp.add(cellHouse.getName());
                    type = cellHouse.getHouseType();
                    tLabel = dictService.selectByFilter(type, "houseType").getLabel();
                    temp.add(tLabel);
                    state = cellHouse.getHouseState();
                    sLabel = dictService.selectByFilter(state, "houseState").getLabel();
                    temp.add(sLabel);
                    temp.add(cellHouse.getArea().toString());
                    temp.add(cellHouse.getPerPrice().toString());
                    temp.add(cellHouse.getOwnerName1());
                    temp.add(cellHouse.getOwnerPhone1());
                    temp.add(cellHouse.getOwnerName2());
                    temp.add(cellHouse.getOwnerPhone2());
                    temp.add(cellHouse.getMemo());
                    dataList.add(temp);
                }
                // 导出标题列
                String[] rows = new String[] { "序号", "区域", "楼栋", "单元", "房号", "房间类型", "房间状态", "面积", "物业费单价", "姓名", "电话",
                        "姓名2", "电话2", "备注" };
                // 导出excel文件每列宽度
                int[] style = new int[] { 5, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 };
                // Excel文件sheet名称
                String sheetName = "小区房屋信息" + DateUtils.getCurrentDate();
                String fileName = "小区房屋信息";
                doExecl(response, fileName, sheetName, dataList, rows, style);
                LogUtils.insertLog("用户导出小区房屋", user.getId(), request);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    /**
     * @Description 通过传入的对象信息集合产生的excel表格<br>
     * @param response
     *            用户响应
     * @param sheetName
     *            excel表名称
     * @param dataList
     *            传入的数据列表
     * @param rows
     *            excel表的列控制，名称
     * @param style
     *            规定列宽等样式
     * @throws Exception
     * @author fangli
     * @date 2016年5月18日
     * @see
     */
    private void doExecl(HttpServletResponse response, String tempName, String sheetName,
            ArrayList<ArrayList<String>> dataList, String[] rows, int[] style) throws Exception {
        // 输出的excel名称为中文，否则发生错误
        String tempFileName = tempName + ".xls";
        String fileName = new String(tempFileName.getBytes("GB2312"), "ISO_8859_1");

        ServletOutputStream fout = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "filename=" + fileName + "");
        JExcelReport jexcelOutStream = new JExcelReport();

        try {
            jexcelOutStream.excelreport(sheetName, dataList, rows, fout, style);
            fout.flush();
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
   
    /**
     * @description 展示业主申请信息详情
     * @param id 业主、房屋关联信息的id
     * @author chenxin
     * @date 2016年9月22日下午3:19:59
     */
    @RequestMapping(value = "/showDetail", method = RequestMethod.GET)
    public String showDetail(Model model, String id) {
        try {
            
            OwnerHouse ownerHouse = ownerHouseService.selectByPrimaryKey(id);//业主房屋关联信息查询
            CellHouse cellHouse = cellHouseService.selectByPrimaryKey(ownerHouse.getHouseId());//业主房屋信息
            User user = userService.selectByPrimaryKey(ownerHouse.getOwnerId());//业主信息
            
            model.addAttribute("cellHouse", cellHouse);
            model.addAttribute("user", user);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "base/cellhouse/cellHouseApplicationDetail";
    }
    
    /**
     * @description 打开业主申请备注填写弹窗
     * @author chenxin
     * @date 2016年9月22日下午4:21:42
     */
    @RequestMapping(value = "/addMemo", method = RequestMethod.GET)
    public String addMemo(Model model,String id) {
        CellHouse cellHouse = cellHouseService.selectByPrimaryKey(id);
        model.addAttribute("cellHouse", cellHouse);
        return "base/cellhouse/addMemo";
    }
    
    /**
     * @description 保存业主申请备注信息
     * @param id 房屋id
     * @param memo 房屋申请备注信息
     * @author chenxin
     * @date 2016年9月22日下午2:04:41
     */
    @RequestMapping(value = "saveMemo")
    @ResponseBody
    public RequestJson saveMemo(String id, String memo, HttpServletRequest request) {
        RequestJson result = new RequestJson();
        User user = (User) request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

        try {
            CellHouse cellHouse = cellHouseService.selectByPrimaryKey(id);
            cellHouse.setMemo(memo);

            cellHouseService.update(cellHouse);
            result.setSuccess(true);
            LogUtils.insertLog("用户添加商户申请备注信息", user.getId(), request);
        } catch (Exception e) {
            result.setSuccess(false);
        }
        return result;
    }

}
